/*
 * @Author: sonss
 * @Date: 2024-08-30 04:37:20
 * @LastEditTime: 2024-09-03 19:09:50
 * @FilePath: /ss-file-antd/src/pages/Assets/File/modules/Edit.tsx
 * @Description:  资源文件编辑
 */
import { Update } from '@/services/assets_file';
import { DrawerForm, ProForm, ProFormText } from '@ant-design/pro-components';
import { message } from 'antd';
import _ from 'lodash';
import { useEffect } from 'react';

type EditModuleProps = {
  record?: ASSETS.FILE.Info;
  onClose?: () => void;
  onSuccess?: () => void;
};

type EditFieldsValue = {
  fileName?: string;
  tags?: string;
};

const EditModule: React.FC<EditModuleProps> = (props) => {
  const [form] = ProForm.useForm<EditFieldsValue>();
  const [messageApi, contextHolder] = message.useMessage();

  useEffect(() => {
    const fieldsValue: EditFieldsValue = _.pick(props.record, 'fileName', 'tags');
    form.setFieldsValue(fieldsValue);
  }, [props.record]);

  const handleOpenChange = (val: boolean) => {
    if (val) {
      return;
    }
    form.resetFields();

    if (props.onClose) {
      props.onClose();
    }
  };

  const finish = async (values: EditFieldsValue) => {
    const formData: ASSETS.FILE.UpdateForm = {
      id: props.record!.id!,
      data: {
        ...values,
      },
    };
    const res = await Update(formData);
    if (res.code !== 0) {
      messageApi.error(res.message);
      return;
    }

    if (props.onSuccess) {
      props.onSuccess();
    }
  };

  return (
    <>
      <DrawerForm
        title="编辑信息"
        form={form}
        drawerProps={{
          destroyOnClose: true,
        }}
        open={true}
        onOpenChange={handleOpenChange}
        onFinish={finish}
        width="35%"
      >
        <ProFormText
          name="fileName"
          width="md"
          label="文件名"
          placeholder="请输入"
          rules={[{ required: true, message: '请输入' }]}
        />
        <ProFormText name="tags" width="xl" label="标签" placeholder="多个请用空格隔开" />
      </DrawerForm>
      {contextHolder}
    </>
  );
};

export default EditModule;
